package jmine.tec.executionlog;

import java.util.ArrayList;
import java.util.List;

import jmine.tec.executionlog.domain.ExecutionLogItem;

/**
 * ExecutionLogContext
 * 
 * @author lundberg
 */
public class ExecutionLogContext {
    private static final long AUTO_SAVE_THRESHOLD = 5000;

    private Long idExecutionLog = null;

    private Long oldestUnsavedItem = null;

    private final List<ExecutionLogItem> unsavedItems = new ArrayList<ExecutionLogItem>();

    private boolean alwaysSave;

    /**
     * @return the idExecutionLog
     */
    public Long getIdExecutionLog() {
        return this.idExecutionLog;
    }

    /**
     * @param idExecutionLog the idExecutionLog to set
     */
    public void setIdExecutionLog(Long idExecutionLog) {
        this.idExecutionLog = idExecutionLog;
    }

    /**
     * Adds an item.
     * 
     * @param item item
     */
    public void addItem(ExecutionLogItem item) {
        this.unsavedItems.add(item);
        if (this.oldestUnsavedItem == null) {
            this.oldestUnsavedItem = System.currentTimeMillis();
        }
    }

    /**
     * @return the unsavedItems
     */
    public List<ExecutionLogItem> retrieveUnsavedItems() {
        List<ExecutionLogItem> result = new ArrayList<ExecutionLogItem>(this.unsavedItems);
        return result;
    }

    /**
     * Limpa a lista de unsavedItems e o oldestUnsavedItem.
     */
    public void clearUnsavedItems() {
        this.unsavedItems.clear();
        this.oldestUnsavedItem = null;
    }

    /**
     * Força {@link ExecutionLogContext#shouldAutoSave()} retornar <code>true</code>.
     */
    public void alwaysSaveMode() {
        this.alwaysSave = true;
    }

    /**
     * Returns true if the unsaved items should be saved now.
     * 
     * @return boolean
     */
    public boolean shouldAutoSave() {
        return this.alwaysSave || (this.hasUnsavedItems() && (System.currentTimeMillis() - this.oldestUnsavedItem > AUTO_SAVE_THRESHOLD));
    }

    /**
     * @return se contém itens não salvos.
     */
    private boolean hasUnsavedItems() {
        return this.oldestUnsavedItem != null && !this.unsavedItems.isEmpty();
    }
}
